import { createStore } from '@/airstore';
import ApiClient from '../services/apiClient';
import { appId } from '../constants';

export default createStore({
  namespace: 'UserStore',
  user: {
    Email: '',
    IsCompanyAdmin: false,
    LoginName: '',
    Mobile: '',
    Name: '',
    OrgCode: '',
    Department: '',
    Password: null,
    WorkNum: '',
    UserId: '',
  },
  idCardNum: {
    IdCard: '',
    workNum: '',
  },
  permissions: [],
  flightWorkers: {
    departments: [
      /*
      {
        value: '1',
        label: '航线维修分部',
        children: [
          {
            value: '0000.0001.0300.0004.0012',
            label: '无损检测车间',
          },
          {
            value: '0000.0001.0300.0004.0009',
            label: '客舱车间',
          },
        ],
      },
      {
        value: '2,',
        label: '定检维修分部',
        children: [
          { value: '0000.0001.0300.0004.0009', label: '客舱车间' },
          { value: '0000.0001.0300.0003.0003', label: '三车间' },
        ],
      },
      */
    ],
    workers: [], // [{id, name, stationCode, teamCode}]
  },

  hasPermission(permission) {
    return (
      __DEV__ ||
      this.user.IsCompanyAdmin ||
      !permission ||
      this.permissions.some(
        (perm) =>
          perm.trim().toLowerCase() ===
          `${appId}:${permission}`.trim().toLowerCase(),
      )
    );
  },
  async getUser() {
    const [userRes, departmentRes] = await Promise.all([
      ApiClient.get('user/user/info'),
      ApiClient.get('user/innerUser/listDepartment'),
    ]);

    const userInfo = userRes.data;
    if (!userRes.errorCode) {
      if (!departmentRes.errorCode && userInfo.OrgCode) {
        const department = departmentRes.data.find(
          (depd) => depd.DepartmentCode === userRes.data.OrgCode,
        );
        if (department) {
          userInfo.Department = department.Name;
        }
      }
      this.setUser(userInfo);
    } else {
      console.log('getUser', userRes);
    }
  },
  setUser(user) {
    this.user = user;
    this.permissions = user.Permissions;
    delete this.user.Permissions;
  },
  // 身份证号获取
  // async getUserIdCard() {
  //   if (this.user.WorkNum !== '') {
  //     const res = await ApiClient.post('jcIdentity/v1/getIdentity', {
  //       jsonResult: JSON.stringify({ WorkNum: this.user.WorkNum }),
  //     });
  //     if (!res.errorCode) {
  //       this.idCardNum = res.data;
  //       res.data[0].IdCard === ''
  //         ? (this.idCardNum.IdCard = '152825199709262726')
  //         : (this.idCardNum.IdCard = res.data[0].IdCard);
  //     }
  //   }
  // },
  setFlightWorkers(acnoUsersData, selUserData) {
    let workers = [];
    const departments = [];
    for (let i = 0; i < acnoUsersData.length; i += 1) {
      // acnoUsersData[i] 对应一个部门下面全部用户
      const deptUsers = acnoUsersData[i];
      if (deptUsers.length > 0) {
        workers = workers.concat(
          deptUsers.map((fwrd) => {
            let checked;
            if (
              selUserData.find(
                (slud) => slud.TS_TaskOperatorId.toString() === fwrd.UserTid,
              )
            ) {
              checked = true;
            }
            return {
              id: fwrd.UserTid,
              name: fwrd.Name,
              stationCode: fwrd.StationCode,
              teamCode: fwrd.TeamCode,
              teamName: fwrd.TeamName,
              checked,
            };
          }),
        );
        if (deptUsers[0].TeamCode === deptUsers[0].SectionCode) {
          // 主部门
          departments.push({
            value: deptUsers[0].TeamCode,
            label: deptUsers[0].TeamName,
            children: [
              {
                value: deptUsers[0].TeamCode,
                label: deptUsers[0].TeamName,
              },
            ],
          });
        } else {
          const dept = departments.find(
            (dptm) => dptm.value === deptUsers[0].SectionCode,
          );
          if (dept) {
            dept.children.push({
              value: deptUsers[0].TeamCode,
              label: deptUsers[0].TeamName,
            });
          }
        }
      }
    }
    this.flightWorkers = { departments, workers };
  },
  async getFlightWorkerUsers(userFilter, selUserFilter) {
    const [fwuRes, fwusRes] = await Promise.all([
      ApiClient.post('mpController/v1/getAcnoUser', {
        jsonResult: JSON.stringify(userFilter),
      }),
      ApiClient.post('mpController/v1/getAcnoUserSelect', {
        jsonResult: JSON.stringify(selUserFilter),
      }),
    ]);
    if (!fwuRes.errorCode) {
      this.setFlightWorkers(fwuRes.data, fwusRes.data || []);
    }
    return fwuRes;
  },
  setFlightWorker(workerItem) {
    this.flightWorkers.workers = this.flightWorkers.workers.map((wrk) => {
      if (wrk.id === workerItem.id) {
        return { ...wrk, ...workerItem };
      }
      return wrk;
    });
  },
  clearFlightWorkers() {
    this.flightWorkers = { departments: [], workers: [] };
  },
});
